/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.customer;

import com.alibaba.fastjson.JSONArray;
import net.dgg.dggcloud.core.util.MapToBeanUtils;
import net.dgg.dggcloud.core.util.NJCodeUtil;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerConstant;
import net.dgg.dggcloud.service.jrcrm.dao.customer.CustomerDao;
import net.dgg.dggcloud.service.jrcrm.entity.customer.Contact;
import net.dgg.dggcloud.service.jrcrm.entity.customer.Customer;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.service.cms.CustomerRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户管理业务处理层
 * @ClassName: CustomerService
 * @Author: 周潮
 * @Date: 2017年11月03 14:34:05
 * @Version V1.0
 */

@Service
public class CustomerService extends BaseService {

    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private CustomerRecordService recordService;
    @Resource
    private NJCodeUtil njCodeUtil;

    /**
     * 查询客户商机列表信息
     * @param map
     * @return
     */
    public List<Map> queryCustomerBusinessList(Map map){
        return customerDao.queryCustomerBusinessList(map);
    }

    /**
     * 查询客户商机列表信息
     * @param map
     * @return
     */
    public Integer queryCustomerBusinessListCount(Map map){
        return customerDao.queryCustomerBusinessListCount(map);
    }

    /**
     * 查询成单客户列表
     * @param map
     * @return
     */
    public List<Map> querySucceedCustomerList(Map map){return customerDao.querySucceedCustomerList(map);}

    /**
     * 查询成单客户列表-count
     * @param map
     * @return
     */
    public Integer querySucceedCustomerListCount(Map map){return customerDao.querySucceedCustomerListCount(map);}

    /**
     * 查询无效库列表信息
     * @param map
     * @return
     */
    public List<Map> queryInvalidCustomerList(Map map){
        return customerDao.queryInvalidCustomerList(map);
    }

    /**
     * 查询无效库列表信息
     * @param map
     * @return
     */
    public Integer queryInvalidCustomerListCount(Map map){
        return customerDao.queryInvalidCustomerListCount(map);
    }

    /**
     * 根据客户id查询客户
     * @param id
     * @return
     */
    public Customer findCustomerById(Long id){
       return repository.get(Customer.class,id);
    }


    /**
     * 保存客户基本信息（客户详情）
     * @param map
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveCustomerByDetail(Map map){
        if(null == map.get("User")){
            throw new BizException("保存客户失败！当前登录人信息获取失败！", 100005);
        }
        if(null == map.get("customer")){
            throw new BizException("保存客户失败！客户信息获取失败！", 100005);
        }
        User user = (User) map.get("User");
        Customer customer = (Customer) map.get("customer");
        if(null == customer){
            throw new BizException("保存客户失败！客户信息获取失败！", 100005);
        }
        if(null == customer.getId()){
            throw new BizException("保存客户失败！客户信息获取失败！", 100005);
        }
        Customer c = this.findCustomerById(customer.getId());
        c.setName(customer.getName());//姓名
        c.setIdCard(customer.getIdCard());//身份证
        c.setSex(customer.getSex());//性别
        c.setAge(customer.getAge());//年龄
        c.setMaritalStatus(customer.getMaritalStatus());//婚姻状况
        c.setChildrenNum(customer.getChildrenNum());//子女情况
        c.setEduBackground(customer.getEduBackground());//学历
        c.setRegisteredResidence(customer.getRegisteredResidence());//户口所在地
        c.setAddress(customer.getAddress());//家庭住址
        c.setEmail(customer.getEmail());//email
        if (c.getIsBuyVip() == null ||  c.getIsBuyVip() != 1){//若曾经选过是   则不用再修改了
            c.setIsBuyVip(customer.getIsBuyVip());//是否购买vip
        }
        //vip 使用次数, 如果选择了是  没有填使用次数则默认为零
        if (c.getIsBuyVip() == 1){
            if (customer.getVipCardUseNumer() == null){
                c.setVipCardUseNumer(0);
            }else {
                c.setVipCardUseNumer(customer.getVipCardUseNumer());
            }
        }
        if(null != customer.getIdCard() && StringUtils.isNotEmpty(c.getIdCard())){
            c.setBirthday(calcBirthday(customer.getIdCard()));//生日
        }else{
            c.setBirthday(customer.getBirthday());//生日
        }
        c.setUpdaterUser(user);
        repository.saveOrUpdate(c);
        //保存操作记录
       // saveCustomerRecord(c.getId(), c.getNo(), Customer.TABLE_NAME, c.getId(), CustomerConstant.CUS_OPERATE_CUS_UPDATE, user.getId(), "修改客户基本信息");
    }

    /**
     * 保存针对客户主体的备注
     * @param map
     * customerId：客户id <br/>
     * no：客户编号 <br/>
     * remark：客户备注 <br/>
     * User：操作人 <br/>
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveCustomerRemark(Map map){
        if(null == map.get("customerId")){
            throw new BizException("保存备注失败，客户不存在！", 100005);
        }
        if(null == map.get("no")){
            throw new BizException("保存备注失败，客户编号错误！", 100005);
        }
        if(null == map.get("remark")){
            throw new BizException("保存备注失败，备注信息为空！", 100005);
        }
        if(null == map.get("User")){
            throw new BizException("保存备注失败，操作人信息不完整！", 100005);
        }
        Long customerId = Long.parseLong(map.get("customerId").toString());
        String no = map.get("no").toString();
        User user = (User) map.get("User");
        String remark = map.get("remark").toString();
        Customer customer = repository.get(Customer.class, customerId);
        if(null == customer){
            throw new BizException("保存备注失败，客户不存在！", 100005);
        }
        customer.setRemark(remark);
        repository.saveOrUpdate(customer);
        saveCustomerRecord(customerId, no, Customer.TABLE_NAME, customerId, CustomerConstant.CUS_OPERATE_CUS_REMARK, user.getId(), remark);
    }

    /**
     * 保存客户模块相关操作记录
     * @param customerId 客户id
     * @param no 客户编号
     * @param tableName 操作表名
     * @param tableId 操作表id
     * @param operateType 操作类型
     * @param operatorId 操作人id
     * @param content 操作内容
     */
    public void saveCustomerRecord(Long customerId, String no, String tableName, Long tableId, String operateType, Long operatorId, String content){
        Map<String, Object> recordMap = new HashMap();
        recordMap.put("tableName", tableName);//操作表名
        recordMap.put("tableId", tableId);//操作表id
        recordMap.put("cusId", customerId);//客户id
        recordMap.put("operateUser", operatorId);//操作人id
        recordMap.put("recordType", operateType);//操作类型
        recordMap.put("content", content);//操作内容
        recordMap.put("ext3", no);//编号
        recordService.saveCustomerRecord(recordMap);
    }

    /**
     * 根据身份证号码计算生日
     * @param idCard
     * @return
     */
    private String calcBirthday(String idCard){
        String birthday = "";
        String yy = "";
        String MM = "";
        String dd = "";
        if(idCard.length() == 18){
            //  通过String[]的substring方法来读取信息
            yy = idCard.substring(6,10);          //出生的年份
            MM = idCard.substring(10,12);       //出生的月份
            dd = idCard.substring(12,14);         //出生的日期
            birthday = yy.concat("-").concat(MM).concat("-").concat(dd);
        }
        return birthday;
    }

    /**
     * 工作台今日生日客户列表查询
     * @param paramMap 参数
     * @return 结果集合
     */
    public List<Map> queryWorkbenchBirthdayCustomerList(Map paramMap) {
        return customerDao.queryWorkbenchBirthdayCustomerList(paramMap);
    }

    /**
     * 工作台今日生日客户数据统计
     * @param paramMap 参数
     * @return 数据条数
     */
    public Integer countWorkbenchBirthdayCustomerList(Map paramMap) {
        return customerDao.countWorkbenchBirthdayCustomer(paramMap);
    }

    /**
     * mq推送客户新增或修改客户消息时，调用该方法进行业务处理
     * @param obj 要处理的客户数据
     */
    public void saveOrUpdateBaseCustomer(Map obj) {
        try {
            List<Contact> contactList = JSONArray.parseArray(obj.get("contacts").toString(), Contact.class);
            obj.remove("contacts");
            Customer customer = (Customer) MapToBeanUtils.MapToBean(Customer.class, obj);
            if(!CustomerConstant.contactWaySet.contains(customer.getContactWay())){//判断联系方式是否存在于iboss
                return;
            }
            //查询客户是否存在，存在则更新，不存在则新建
            Customer updateCustomer = repository.get(Customer.class, customer.getId());
            if(null == updateCustomer){//新增
                repository.save(customer);
                saveCustomerRecord(customer.getId(), customer.getNo(), Customer.TABLE_NAME, customer.getId(), CustomerConstant.CUS_OPERATE_CUS_SAVE, 1L, "新增客户");
                for (Contact contact : contactList) {
                    if(!CustomerConstant.contactWaySet.contains(contact.getContactWay())){//判断联系方式是否存在于iboss
                        return;
                    }
                    contact.setStatus(contact.getStatus().equals("1") ? CustomerConstant.CUS_CONTACT_STATUS_1 : CustomerConstant.CUS_CONTACT_STATUS_0);
                    repository.save(contact);
                    saveCustomerRecord(customer.getId(), customer.getNo(), Contact.TABLE_NAME, contact.getId(), CustomerConstant.CUS_OPERATE_CONTACT_SAVE, 1L, "新增联系人");
                }
            }else {//更新
                if(!CustomerConstant.contactWaySet.contains(customer.getContactWay())){//判断联系方式是否存在于iboss
                    return;
                }
                updateCustomer.setName(customer.getName());
                updateCustomer.setIdCard(customer.getIdCard());
                updateCustomer.setCustomerType(customer.getCustomerType());
                updateCustomer.setMainContactId(customer.getMainContactId());
                updateCustomer.setMainContactNo(customer.getMainContactNo());
                updateCustomer.setMainContactNoBak(njCodeUtil.decrypt(customer.getMainContactNo()));
                updateCustomer.setMainContactName(customer.getMainContactName());
                updateCustomer.setContactWay(customer.getContactWay());
                updateCustomer.setNo(customer.getNo());
                updateCustomer.setCustomerPhone(customer.getCustomerPhone());
                updateCustomer.setCustomerPhoneBak(njCodeUtil.decrypt(customer.getCustomerPhone()));
                repository.getSession().evict(customer);
                repository.saveOrUpdate(updateCustomer);
                saveCustomerRecord(updateCustomer.getId(), updateCustomer.getNo(), Customer.TABLE_NAME, updateCustomer.getId(), CustomerConstant.CUS_OPERATE_CUS_UPDATE, 1L, "修改客户基本信息");
                for (Contact contact : contactList) {
                    if(!CustomerConstant.contactWaySet.contains(contact.getContactWay())){//判断联系方式是否存在于iboss
                        return;
                    }
                    Contact updateContact = repository.get(Contact.class, contact.getId());
                    updateContact.setStatus(contact.getStatus().equals("1") ? CustomerConstant.CUS_CONTACT_STATUS_1 : CustomerConstant.CUS_CONTACT_STATUS_0);
                    updateContact.setNo(contact.getNo());//联系人号码
                    updateContact.setNoBak(njCodeUtil.decrypt(contact.getNo()));//联系人号码
                    updateContact.setName(contact.getName());//联系人姓名
                    updateContact.setContactWay(contact.getContactWay());//联系方式
                    updateContact.setCustomerId(contact.getCustomerId());//客户id
                    repository.getSession().evict(contact);
                    repository.saveOrUpdate(updateContact);
                    saveCustomerRecord(customer.getId(), customer.getNo(), Contact.TABLE_NAME, updateContact.getId(), CustomerConstant.CUS_OPERATE_CONTACT_UPDATE, 1L, "修改联系人");
                }
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存客户信息
     * @param customer
     */
    public void updateCustomer(Customer customer) {
        this.repository.saveOrUpdate(customer);
    }

    public List<Map> queryCustomerList(Map map){
        return customerDao.queryCustomerList(map);
    }
}
